﻿using System;
using System.Configuration;
using System.IO;
using System.Web;
using Shuba.Business;
using Shuba.Model;

namespace Shuba.Web.mobile
{
    public partial class user_device_upload : basePage
    {
        string msg = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string acl = GetUserAccess("MSTR_USER_DEVICE");

                if (!IsUserAdd(acl))
                {
                    msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }

                LabelTitle.Text = GetPageTitle("MSTR_USER_DEVICE");
            }
        }

        private bool IsValidExt(string ext)
        {
            bool fileOk = false;
            String[] allowedExtensions = { ".txt", ".csv" };
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (ext == allowedExtensions[i])
                {
                    fileOk = true;
                    break;
                }
            }

            return fileOk;
        }

        private UserDeviceInfo Parse(string data)
        {
            var fields = data.Split('\t');
            if (fields.Length > 2)
                throw new Exception("Invalid row");

            UserDeviceInfo info = new UserDeviceInfo();

            info.NIP = fields[0].Trim();
            info.IMEI = fields[1].Trim();
            info.ActType = "UPLOAD";
            info.EntryBy = HttpContext.Current.User.Identity.Name;
            info.EntryDate = ProcessingDate();
            info.UpdateBy = HttpContext.Current.User.Identity.Name;
            info.UpdateDate = ProcessingDate();

            return info;
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                try
                {
                    Upload();
                }
                catch (Exception ex)
                {
                    lblStatus.Text = ex.Message;
                }
            }
        }

        private void Upload()
        {
            string path = Server.MapPath("~/uploads/");
            int ErrLine = 0;

            if (!FileUpload1.HasFile)
                throw new Exception("Empty file");

            String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();

            if (!IsValidExt(fileExtension))
                throw new Exception("Invalid file extension!");

            status.Visible = true;
            string fName = path + Session["UserID"].ToString() + FileUpload1.FileName;
            FileUpload1.PostedFile.SaveAs(fName);

            var filestream = File.OpenText(fName);
            string contents = filestream.ReadToEnd();
            filestream.Close();

            var bl = new UserDevice();

            var rows = contents.Split('\n');

            for (var i = 0; i < rows.Length; i++)
            {
                try
                {
                    UserDeviceInfo info = Parse(rows[i]);
                    bl.Save(info);
                }
                catch
                {
                    ErrLine++;
                }

            }

            File.Delete(fName);
            AddLog("UPLOAD", "UPLOAD USER DEVICE");

            msg = String.Format("Success = {0}, Error = {1}", rows.Length - ErrLine, ErrLine);
            lblStatus.Text = msg;
            FileUpLoadValidator.Visible = false;
            AlertAndRedirect(msg, "user_device_list.aspx");
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("user_device_list.aspx");
        }
    }
}
